//zt-home、gs、yy-home
const allowUrls = [
  "http://192.168.199.152:5173",
  "http://192.168.199.151:5173",
  "http://192.168.10.2:5173",
  "http://192.168.10.4:5173",
  "http://192.168.124.10:5173",
  "https://account.dcloud.net.cn"
  
];

export const getParentUrl = function () {
  var url = "";
  if (parent !== window) {
    try {
      url = parent.location.href;
    } catch (e) {
      url = document.referrer;
      if (allowUrls.some((el) => e.message.indexOf(el) !== -1)) {
        url = "https://account.dcloud.net.cn";
      }
	  if(!url){
		  url = "https://account.dcloud.net.cn";
	  }
    }
  }
  return url;
};
export const checkIsInValidIframe = () => {
  return getParentUrl() === "https://account.dcloud.net.cn";
};

export const receiveMsgFromIDEA = (callback = ({ data = {} }) => {}) => {
  const listenMsgCallback = (e) => {
    // 通过origin对消息进行过滤，避免遭到XSS攻击
    if (e.origin.startsWith("https://account.dcloud.net.cn") || e.origin.startsWith("file://")) {
      const d = e?.data ?? {};
      callback({
        data: d,
      });
    }
  };
  window.addEventListener("message", listenMsgCallback, false);
  return {
    listenMsgCallback,
  };
};

export const sendMsgToIDEA = async (
  getMsg = ({ parentUrl = "" }) => {
    return "";
  },
  awaitResCallback = null,
  timeout = 5000
) => {
  const parentUrl = getParentUrl();
  if (parentUrl.startsWith("https://account.dcloud.net.cn") || parentUrl.startsWith("file:///")) {
    window.top.postMessage(
      getMsg({
        parentUrl,
      }),
      "*"
    );
    if (awaitResCallback && typeof awaitResCallback === "function") {
      let res = null;
      const callback = async ({ data }) => {
        res = await awaitResCallback({ data });
      };
      const { listenMsgCallback } = receiveMsgFromIDEA(callback);
      let timeCount = 0;
      const mockWait = async () => {
        return new Promise(async function (resolve, reject) {
          const timer = setInterval(() => {
            timeCount++;
            if (res || timeCount >= timeout / 1000) {
              clearInterval(timer);
              window.removeEventListener("message", listenMsgCallback, false);
              resolve(true);
            }
          }, 1000);
        });
      };
      await mockWait();
      return Promise.resolve(res);
    } else return Promise.resolve(null);
  } else {
    return Promise.resolve(null);
  }
};

export default {
  getParentUrl,
  checkIsInValidIframe,
  receiveMsgFromIDEA,
  sendMsgToIDEA,
};
